import DCOracle2
import os
import random
import unittest

connstrings = {
    "bane":  "scott/tiger",
    "bane.mi.org":  "scott/tiger",
    "ire.mi.org":  "scott/tiger@bane",
    "fizzle.mi.org":  "scott/tiger@bane",
    "sidhe.mi.org":     "scott/tiger@sidhe",
    "djinn.digicool.com":  "scott/tiger",
    "djinn.zope.com":  "scott/tiger",
    "djinn":  "scott/tiger"
}


def getConnectionString():
    hostname = os.uname()[1]

    # support for historical pairs above
    if connstrings.has_key(hostname): return connstrings[hostname]

    # look at the environment variables
    connstring = os.environ.get('DCORACLE_TEST_CONNSTRING')
    if connstring:
        return connstring
    
    raise KeyError,"Please specify connection string for tests in "\
                   "DCORACLE_TEST_CONNSTRING environment variable"

class TestCase(unittest.TestCase):

    tables_to_drop = ()
    
    def setUp(self):
        
        self.db = db = DCOracle2.connect(getConnectionString())
        self.c  = c  = db.cursor()

        for tablename in self.tables_to_drop:
            try:
                c.execute('drop table '+tablename)
            except DCOracle2.DatabaseError:
                pass

        username,password,dbname = self._getConnDetails()
        self.username = username.upper()
        
    def tearDown(self):

        self.c.close()

    def _getBinary(self,kb):

        return ''.join([
            chr(random.randint(0,255))
            for x
            in range(kb*1000)
            ])

    def _getConnDetails(self):
        dsn = getConnectionString()
        try:
            userpass, dbname = dsn.split("@")
        except ValueError:
            userpass = dsn
            dbname = ""

        try:
            username, password = userpass.split("/")
        except ValueError:
            username = dsn
            password = ""

        return username,password,dbname
